package businessLogic;

import Definitions.ManagerException;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.Manager;

/**
 *
 * @author kidney
 */
@Stateless
public class CreateUserBean implements CreateUserBeanLocal {

    @PersistenceContext
    private EntityManager em;

    /*
     * Registrace nového uživatele.
     * @param login String, password String
     */
    public void createUser(String login, String password) throws ManagerException {
        if (isLoginAlreadyUsed(login)) {
            throw new ManagerException("User with this login already exists.");
        }
        Manager manager = new Manager();
        manager.setLogin(login);
        manager.setPassword(password);
        manager.setIsAdmin('n');
        em.persist(manager);
    }

    /**
     * Vrátí true, pokud již existuje uživatel s daným loginem
     * @param userLogin String
     * @return boolean
     */
    private boolean isLoginAlreadyUsed(String userLogin) {
        List<Manager> mng = em.createQuery("SELECT m FROM Manager m WHERE m.login=:newName").setParameter("newName", userLogin).getResultList();
        return (!mng.isEmpty());
    }
 
}
